<template>
    <div class="editMed">
        <el-card>
            <!-- 返回按钮 -->
            <el-button type="info" size="small" icon="el-icon-arrow-left"
                @click="backToPrev">
                返回</el-button>
            <!-- 添加表单 -->
            <el-form :model="editForm" size="small" class="editForm" ref="ruleForm" :rules="rules">
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item prop="typeId">
                            <span slot="label">
                                <span class="labelText">分类</span>
                            </span>
                            <div class="choose">
                                <el-select v-model="editForm.typeId"
                                    placeholder="选择分类">
                                    <el-option v-for="item in medClassList" :label="item.drugTypeName
                                    " :value="item.id"
                                        :key="item.id"></el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                        <el-form-item prop="name">
                            <span slot="label">
                                <span class="labelText">药品名称</span>
                            </span>
                            <el-input v-model="editForm.name"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">条形码</span>
                            </span>
                            <el-input v-model="editForm.barCode"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">单位</span>
                            </span>
                            <el-input v-model="editForm.unitName"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">标签</span>
                            </span>
                            <el-input v-model="editForm.tag"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="status">
                            <span slot="label">
                                <span class="labelText">状态</span>
                            </span>
                            <div class="choose">
                                <el-select v-model="editForm.status"
                                    placeholder="选择状态">
                                    <el-option label="有效" value="0"></el-option>
                                    <el-option label="无效" value="1"></el-option>
                                </el-select>
                            </div>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">药品编号</span>
                            </span>
                            <el-input v-model="editForm.id" readonly></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">型号</span>
                            </span>
                            <el-input v-model="editForm.serialNumber"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">数量</span>
                            </span>
                            <el-input v-model="editForm.num" readonly>
                                <el-button slot="suffix" type="primary" size='mini'
                                    @click="stockModel">
                                    <i class="el-icon-box"></i>
                                    库存</el-button>
                            </el-input>
                        </el-form-item>
                        <el-form-item prop="providerId">
                            <span slot="label">
                                <span class="labelText">供应商</span>
                            </span>
                            <el-input placeholder="请查找供应商" readonly value=""
                                v-model="supplierName">
                                <el-button slot="suffix" type="success" size='mini'
                                    @click="searchSupplier">
                                    <i class="el-icon-search"></i>
                                    查找</el-button>
                            </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <hr>
                <el-row :gutter="20">
                    <el-col :span="12">
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">客户单价</span>
                            </span>
                            <el-input v-model="editForm.price"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">特价</span>
                            </span>
                            <el-input v-model="editForm.salePrice"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label">
                                <span class="labelText">上传图片</span>
                            </span>
                            <el-upload action="none" list-type="picture-card"
                                :auto-upload="false" :on-change="checkType" :file-list="fileImgList">
                                <i class="el-icon-plus"></i>
                            </el-upload>
                            <el-dialog>
                                <img width="100%" alt="" :src="dialogImageUrl">
                            </el-dialog>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item prop="costPrice">
                            <span slot="label">
                                <span class="labelText">成本价</span>
                            </span>
                            <el-input v-model="editForm.costPrice"></el-input>
                        </el-form-item>
                        <el-form-item>
                            <span slot="label" class="sales">
                                <span class="labelText">是否销售</span>
                            </span>
                            <el-switch v-model="editForm.isSales"
                                active-color="#13ce66" active-value="0"
                                inactive-value="1">
                            </el-switch>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-form-item class="subBtn">
                    <el-button type="primary"
                        @click="onSubmit('ruleForm')">保存</el-button>
                    <el-button @click="cancelBtn">取消</el-button>
                </el-form-item>
            </el-form>
            <!-- 模态框——选择供应商 -->
            <el-dialog title="供应商查找" :visible.sync="dialogTableVisible">
                <el-card>
                    <el-input placeholder="请输入内容" class="input-with-select"
                        width="200" v-model="normalSearchInput">
                        <el-button slot="append" icon="el-icon-search"
                            @click="normalSearch"></el-button>
                    </el-input>
                    <el-table :data="supplierData">
                        <el-table-column property="providerType" label="类型"
                            width="150"></el-table-column>
                        <el-table-column property="name" label="供应商名称"
                            width="200"></el-table-column>
                        <el-table-column property="contact"
                            label="联系人"></el-table-column>
                        <el-table-column property="username"
                            label="负责人"></el-table-column>
                        <el-table-column property="status" label="状态">
                            <template slot-scope="scope">
                                <el-tag disable-transitions type="success"
                                    v-if="scope.row.status == 0">有效</el-tag>
                                <el-tag disable-transitions type="info"
                                    v-if="scope.row.status == 1">无效</el-tag>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作" width="120" fixed="right">
                            <template slot-scope="scope">
                                <el-button type="success" size="mini"
                                    @click="chooseSupplier(scope.row)">
                                    <i class="el-icon-plus"></i>
                                    选择该供应商
                                </el-button>
                            </template>·
                        </el-table-column>
                    </el-table>
                    <!-- 分页器 -->
                    <Pagination :total="total" :pageSize="pageSize"
                        @getPagination="getPagination"></Pagination>
                </el-card>
            </el-dialog>

            <!-- 模态框——修改库存 -->
            <el-dialog title="出库入库" :visible.sync="stockDialogTableVisible">
                <el-card>
                    <div>
                        <h4 style="line-height: 30px;">请输入修改库存数量</h4>
                        <el-input placeholder="修改库存数量" v-model="stockForm.num">
                        </el-input>
                        <h4 style="line-height: 30px;">请输入备注</h4>
                        <el-input type="textarea"
                            v-model="stockForm.remark"></el-input>
                    </div>

                    <div class="stockBtn">
                        <el-button type="success"
                            @click="addStock(1)">入库</el-button>
                        <el-button type="warning"
                            @click="outStock(0)">出库</el-button>
                    </div>

                </el-card>
            </el-dialog>
        </el-card>

    </div>
</template>
  
<script>

import dayjs from 'dayjs';
import Pagination from '@/components/Pagination';
export default {
    name: '',
    components: {
        Pagination
    },
    data() {
        return {
            supplierName: '',
            normalSearchInput: '',
            //上传列表
            //数据回显
            dialogImageUrl:'',
            fileImgList:[],
            headImgFile: '',
            showImg:'',
            //规则
            rules:{
                typeId: [
                    { required: true, message: '请选择分类' }
                ],
                name: [
                    { required: true, message: '请填写药品名称', trigger: 'change' }
                ],
                providerId:[
                     { required: true, message: '请选择供应商' }
                ],
                costPrice:[
                     { required: true, message: '请填写成本价' }
                ]
            },
            editForm: {
                "barCode": "",
                "costPrice": '',
                "createTime": '',
                "details": "",
                "id": 0,
                "img": "",
                "isDeleted": 0,
                "isSales": '',
                "model": "",
                "name": "",
                "num": '',
                "price": '',
                "providerId": '',
                "salePrice": '',
                "serialNumber": "",
                "status": 0,
                "tag": "",
                "typeId": 0,
                "unitName": "",
                "updateTime": ''
            },
            originForm: {

            },
            //图片信息
            imgForm: {
                imgData: '',
                id: ''
            },
            //药品分类列表
            medClassList: [],
            stockDialogTableVisible: false,
            dialogTableVisible: false,
            //供应商数据
            supplierData: [],
            total: 0,
            currentPage: 1,
            pageSize: 10,
            //出库入库
            stockForm: {
                id: '',
                type: '',
                num: 10,
                remark: '',
            }
        }
    },
    created() {
        this.getMedClassList(1, 100)
    },
    mounted() {
        this.originForm = { ...this.$route.query };
        console.log(this.originForm);
        this.editForm.id = this.originForm.id;
        this.editForm.name = this.originForm.drugName;
        // this.editForm.costPrice=this.originForm.price
        this.editForm.createTime = this.originForm.createTime
        // this.editForm.details=this.originForm
        this.editForm.img = this.originForm.img
        this.editForm.isDeleted = 0
        this.editForm.model = this.originForm.model
        this.editForm.num = this.originForm.num
        this.editForm.price = this.originForm.price
        // this.editForm.salePrice=this.originForm
        // this.editForm.serialNumber=this.originForm
        this.editForm.status = this.originForm.status
        this.editForm.providerId=this.originForm.providerId
        this.editForm.typeId = this.originForm.typeId
        this.editForm.unitName = this.originForm.unitName
        this.editForm.updateTime = this.originForm.updateTime

        if (this.editForm.img) {
                this.fileImgList.push({
                	//由于图片
                    name: 'img',
                    url: this.$host+this.editForm.img,
                })
            console.log('初始list', this.fileImgList);
        }
    },
    methods: {
        dayjs,
        async getMedClassList(currentPage, pageSize) {
            let res = await this.$api.medicine.getMedClassList({ currentPage, pageSize })
            //列表
            if (res.data.code === 200) {
                this.medClassList = res.data.data;
                //页码
                this.total = res.data.data.length;
                console.log(this.medClassList);
            } else {
                console.log('请求失败');
                this.medClassList = []
                this.pageSize = 0;
                this.total = 1;
            }
        },

        //返回上一级
        backToPrev() {
            this.$router.push('/medicine/medManage')
        },
        //取消
        cancelBtn() {
            this.$router.push('/medicine/medManage')
        },
        //获取点击的页码-------------------------------
        getPagination(page) {
            this.currentPage = page;
            this.getSupperList(this.currentPage, this.pageSize);
        },
        //库存数量------------修改-------
        stockModel() {
            this.stockDialogTableVisible = true;
            this.stockForm.id = this.originForm.id;
        },
        addStock(params) {
            this.stockForm.type = params;
            this.editForm.stock += this.stockForm.num;
            console.log(this.stockForm);
            this.$api.medicine.medStockChange(this.stockForm).then(resp => {
                console.log(resp);
            })
            this.stockDialogTableVisible = false;
        },
        outStock(params) {
            if (this.editForm.num < this.stockInputNum) {
                this.$message.warning('库存数量不足，请重新修改')
            } else {
                this.stockForm.type = params;
                this.editForm.num -= this.stockForm.num;
                this.$api.medicine.medStockChange(this.stockForm).then(resp => {
                    console.log(resp);
                    this.stockDialogTableVisible = false;
                })
            }
        },
        //--------------------供应商模态框
        searchSupplier() {
            this.dialogTableVisible = true;
            this.getSupplierList(this.currentPage, this.pageSize);
        },
        async getSupplierList(currentPage, pageSize) {
            let res = await this.$api.supply.getAllSupplierList({ currentPage, pageSize })
            //供应商列表
            console.log(res.data.data.list);
            if (res.data.code === 200) {
                this.supplierData = res.data.data.list;
                //页码
                this.total = res.data.data.total;
            } else {
                console.log('请求失败');
                this.supplierData = []
                this.pageSize = 0;
                this.total = 1;
            }
        },
        //-------普通查找
        async normalSearch() {
            let res = await this.$api.supply.findSupplier(this.currentPage, this.pageSize, this.normalSearchInput.toString());
            this.supplierData = res.data.data.list;
            this.total = res.data.data.total
            // console.log(res);
        },
        //--------------------供应商选择
        chooseSupplier(row) {
            console.log(row.id);
            this.editForm.providerId = row.id;
            this.supplierName = row.name;
            this.dialogTableVisible = false;
        },
        //--------------------提交添加
           //提交添加
        onSubmit(formName) {
            this.$refs[formName].validate((valid) => {
                if(valid){
                    this.editForm.createTime = new Date(dayjs().format("YYYY-MM-DD HH:mm:ss")).toISOString();
            this.$api.medicine.editMed(this.editForm).then(res=>{
                console.log(res);
            if (res.data.code === 200) {
                this.imgForm.id = this.editForm.id;
                let formData = new FormData();
                //文件对象
                formData.append('file', this.headImgFile.raw)
                formData.append('id',this.imgForm.id)
                console.log(formData.get('file'));
                this.$axios({
                    url: '/drugManagement/drugManagement/addDrugImg',
                    method: 'post',
                    headers:{
                        'Content-Type': 'multipart/form-data'
                    },
                    data: formData
                }).then(resp => {
                    //跳转到列表页面
                    console.log(resp);
                    this.$router.push('/medicine/medManage')
                    //提示
                    this.$message({
                        message: '恭喜你，修改药品成功',
                        type: 'success'
                    });
                }).catch(err => {
                    this.$Message.error('error', '请求错误')
                })

            } else {
                //错误信息提示
                this.$message.error('出现错误，添加失败');
            } 
                })
            }else{
                this.$message.error('请填写必填项')
            }})
          
           
        },
        //确定上传文件
        checkType(file, fileList) {
            //截取文件类型
            let fileType = file.name.substring(file.name.lastIndexOf('.') + 1);
            fileList = [];
            if (fileType !== 'jpeg' && fileType !== 'jpg' && fileType !== 'png') {
                this.$Message.error('error', '图片格式不正确');
                return false
            }
            this.headImgFile = file;
            this.imgForm.imgData = this.headImgFile;
            console.log(this.headImgFile);
        }

    }
}
</script>

<style scoped>
.editMed {
    margin: 20px 5px 0;
}

.labelText {
    font-size: 14px;
    font-weight: 600;
    color: #000;
}

hr {
    height: 0px;
    border: 1px solid #6c7b8b;
}

.subBtn {
    text-align: center;
}

.stockBtn {
    margin-top: 20px;
    text-align: center;
}

/* element样式修改 */
.sales {
    float: none;
}

.choose>>>.el-select {
    display: block;
}

.dateChoose>>>.el-date-editor {
    display: block;
    width: 100%;
}

.dateChoose>>>.el-input__prefix {
    top: 17px;
}

.choose>>>.el-select .el-input__suffix {
    top: 15px;
}
</style>